package com.b511.swpu.cementbackend.repository;

import com.b511.swpu.cementbackend.entity.MetaDict;
import com.b511.swpu.cementbackend.entity.SysCompany;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface SysCompanyRepository extends JpaRepository<SysCompany, Long>, JpaSpecificationExecutor<SysCompany> {

    @Query(value = "SELECT MAX (sc.code) FROM SysCompany sc WHERE LENGTH(sc.code)=:level1CodeLength")
    String findMaxLevel1Code(@Param("level1CodeLength") int level1CodeLength);

    //    @Query(value = "SELECT MAX (CODE) FROM META_DICT WHERE SUBSTR(CODE, 0, ?1)=?2", nativeQuery = true)
    @Query(value = "SELECT MAX (sc.code) FROM SysCompany sc WHERE SUBSTRING(sc.code, 0, :parentCodeLength) = :parentCode")
    String findMaxLevel2Code(@Param("parentCodeLength") int parentCodeLength, @Param("parentCode") String parentCode);

    @Modifying
    @Query("UPDATE SysCompany sc SET sc.label = :label WHERE sc.code = :code")
    void updateCompanyName(@Param("code") String code, @Param("label") String label);

    List<SysCompany> findByIsEnableTrue();

    void deleteByCode(String code);

    SysCompany findByLabel(String label);

}
